<template>
  <q-dialog  v-model="printerDiag"> 
  <NFCPrinter v-if="part_id" :part_id="part_id"></NFCPrinter>
</q-dialog>
<q-dialog v-model="fitDiag">
  <div>
    <OrderFitmentBox
      :actions="'Fitment'"
      @update="callFitment"
      @close="fitDiag = false"
      :sn="editRow.serial_no"
      :description="editRow.description"
    ></OrderFitmentBox>
  </div>
</q-dialog>

<q-dialog v-model="defitDialog">
  <MyDialog
    title="defitment"
    :content="`Defit: Stock Code: ${editRow.stock_code} , Serial No :${editRow.serial_no}`"
    :ok="() => defitment()"
  >
  </MyDialog>
</q-dialog>

<q-card-actions align="right" v-if="!checkedDetail">
  <div class="text-red q-pa-sm">
    <div>
      {{ 'Please confirm the part detail before start the order' }}
    </div>
  </div>
  <!-- <q-btn @click="checkDialog = true" class="default-btn" label="Check" /> -->
  <!--   <q-btn
    v-if="showConfirm"
    @click="openConfirmDialog"
    class="yellow-btn"
    label="Confirm"
  /> -->
  <q-btn
    v-if="!checkedDetail"
    @click="openConfirmDialog"
    class="yellow-btn"
    label="Confirm"
  />
</q-card-actions>
<q-dialog persistent v-model="checkDialog">
  <CheckPartDetail
    :order_id="myOrderId"
    @compare="compareFn"
  ></CheckPartDetail>
</q-dialog>

<q-dialog v-model="confirmDialog">
  <CheckConfirmList
    :serials="serials"
    @update="updateConfirm"
  ></CheckConfirmList>
</q-dialog>

  <q-table
    v-if="fail_parts"
    class="my-table card-radius"
    :rows="parts"
    :columns="cols"
    :rows-per-page-options="[9999]"
    wrap-cells
  >
    <template v-slot:body-cell-status="props">
      <q-td
        :class="props.row.serial_no==''? 'missing' : fail_parts[props.row.stock_code+props.row.serial_no]?'fail':'pass'"
        :props="props"
      >
        <div class="text-left">
          <!-- <div v-for="(item, index) in getPartsStatus(
              props.row.serial_no,
              props.row.stock_code,
              props.row.sw_ver,
              props.row.hw_ver
            )?.split(',')" :key="index">
              {{ item }}
          </div> -->
          {{ props.row.serial_no==''? 'missing' : fail_parts[props.row.stock_code+props.row.serial_no]?'fail':'pass' }}
        </div>
        <!--  <q-tooltip class="bg-indigo" :offset="[10, 10]">
        {{
          getPartsStatus(
            props.row.serial_no,
            props.row.stock_code,
            props.row.sw_ver,
            props.row.hw_ver
          )
        }}
      </q-tooltip> -->
      </q-td>
    </template>

    <template v-slot:body-cell="props">
      <q-td
      :class="props.row.serial_no==''? 'missing' : fail_parts[props.row.stock_code+props.row.serial_no]?'fail':'pass'"

      >
        {{ props.value }}
      </q-td>
    </template>

    <template v-slot:body-cell-serial_no="props">
      <q-td
        :class="
          props.row.serial_no==''? 'missing' : fail_parts[props.row.stock_code+props.row.serial_no]?'fail':'pass'
        "
      >
        {{ props.value }}

        <ObsolescenceTip
          v-if="props.row.part && props.row.part.obsolescence == 1"
        ></ObsolescenceTip>
      </q-td>
    </template>

    <template v-slot:body-cell-action="props">
      <q-td
        :class="props.row.serial_no==''? 'missing' : fail_parts[props.row.stock_code+props.row.serial_no]?'fail':'pass'"
      >
        <div class="">
          <q-btn
            class="q-ma-sm e-form-btn"
            size="sm"
            :disable="readOnly"
            rounded
            style="color: #303cbb"
            @click="fitment(props.row)"
          >
            <div class="fal">
              <!--  <img :src="defitIcon" /> -->
              <span class="q-px-sm cap"> fit </span>
            </div>
          </q-btn>

          <q-btn
            class="q-ma-sm e-form-btn"
            size="sm"
            :disable="readOnly"
            rounded
            style="color: #b42c2c"
            @click="defitmentFn(props.row)"
          >
            <div class="fal">
              <!--  <img :src="defitIcon" /> -->
              <span class="q-px-sm cap"> defit </span>
            </div>
          </q-btn>

          <div v-show="false">
            <vue-qr
              ref="myQr"
              :id="`qr-${props.row.stock_code}`"
              :text="getQRCODE(props.row.stock_code, props.row.serial_no)"
              :size="100"
              :margin="0"
            ></vue-qr>
          </div>
          <q-btn
            :disable="readOnly"
            size="sm"
            class="q-ma-sm e-form-btn cap"
            @click="printQrCode(props.row)"
            >print</q-btn
          >
        </div>
      </q-td>
    </template>
    </q-table>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import { Parts, RepairOrderCheckStatus, RepairOrderParts } from 'src/services/type';
import defitIcon from 'src/assets/style/defitment.png';
import { ref, computed } from 'vue';
import {
getCheckStatus,
getOrderParts,
orderPartDefitment,
orderPartFitment,
} from 'src/services/repairService';
import OrderFitmentBox from 'src/components/fitment/OrderFitmentBox.vue';
import { useVersionStore } from 'src/stores/versionStore';
import { getPartsStatus } from 'src/utils/getPublic';
import CheckPartDetail from 'src/components/maintenance/CheckPartDetail.vue';
import CheckConfirmList from './CheckConfirmList.vue';
import { formatDateTimeString } from 'src/utils/dateUtils';
import vueQr from 'vue-qr/src/packages/vue-qr.vue';
import MyDialog from '../container/MyDialog.vue';
import { resolveDjangoUrl } from 'src/boot/axios';
import ScrollArea from '../ScrollArea.vue';
import ObsolescenceTip from 'src/components/ObsolescenceTip.vue';
import { parsePartQR } from 'src/utils/parseQRCodeUtils';
import NFCPrinter from 'src/components/printer/NFCPrinter.vue'

const props = withDefaults(
defineProps<{
  orderId: number;
  stockCode: string;
  editable: boolean;
  checked: boolean;
  isReadOnly: boolean;
}>(),
{
  editable: true,
}
);
const printerDiag = ref(false)

const part_id = ref(null)

const readOnly = ref(false);
if (props.isReadOnly) {
readOnly.value = true;
}

const myOrderId = ref();

const emit = defineEmits(['update', 'updateChecked']);
const checkedDetail = ref(false);
if (props.checked) {
checkedDetail.value = true;
}
const versionStore = useVersionStore();

const $q = useQuasar();
const id = ref(0);
const editRow = ref();
const fitDiag = ref(false);
const confirmDialog = ref(false);
const defitDialog = ref(false);
const checkDialog = ref(false);
const showConfirm = ref(false);
const serials = ref<string[]>([]);
const compareList = ref<string[]>([]);
const parts = ref<RepairOrderParts[]>([]);
const align = 'left';
const cols = [
{
  name: 'description',
  label: 'Short Description',
  field: 'description',
  sortable: true,
  align,
},
{
  name: 'status',
  label: 'Status',
  field: 'status',
  sortable: true,
  align,
},
{
  name: 'last_check_out',
  label: 'Last Check Out',
  field: (row) =>
    row.parts ? formatDateTimeString(row.part.last_check_out) : '',
  sortable: true,
  align,
},
{
  name: 'serial_no',
  label: 'Serial No',
  field: 'serial_no',
  sortable: true,
  align,
},
];
if (props.editable) {
cols.push({
  name: 'action',
  label: 'Action',
  field: 'action',
  sortable: false,
  align,
});
/*   cols.push({
  name: 'qrcode',
  label: 'QR CODE',
  field: 'qrcode',
  sortable: false,
  align,
}); */
}
/* if (props.checkable) {
cols.push({
  name: 'check',
  label: '',
  field: 'check',
  align,
});
} */

function fitment(row: RepairOrderParts) {
editRow.value = { ...row };
fitDiag.value = true;
}

if (props.checked) {
checkedDetail.value = true;
}

function openConfirmDialog() {
serials.value = [];
for (let part of parts.value) {
  if (
    !serials.value.includes(part.serial_no) &&
    !compareList.value.includes(part.serial_no)
  ) {
    serials.value.push(part.serial_no);
  }
}

//  if all seral is checked then no need to pop up
for (let i in parts.value) {
  const part = parts.value[i];
  if (!compareList.value.includes(part.serial_no)) {
    confirmDialog.value = true;
    return;
  }
}
updateConfirm();
}

function updateConfirm() {
// autoDefitment();

emit('updateChecked');
checkedDetail.value = true;
confirmDialog.value = false;
}

async function autoDefitment() {
for (let part of parts.value) {
  if (!compareList.value.includes(part.serial_no)) {
    await orderPartDefitment(part.id);
  }
}
initData();
emit('update');
}

function checkConfirm(sn: string) {
if (compareList.value.includes(sn)) {
  return 'confirm';
}
}

function compareFn(string: string) {
showConfirm.value = true;
if (parts.value.map((v) => v.serial_no).includes(string)) {
  $q.notify({
    color: 'positive',
    position: 'center',
    message: 'Checked ' + string,
    timeout: 200,
  });
}
if (compareList.value.includes(string)) {
  return;
}
if (string == '') {
  return;
}
compareList.value.push(string);
}

async function callFitment(string: string) {
if (string.includes('{') && string.includes('}')) {
  // to do get part hard time replacement id
  const obj = await parsePartQR(string);

  const res = await orderPartFitment(
    editRow.value.repair_order,
    editRow.value.id,
    obj.SN
  );
  if (res.data) {
    if (res.data.code == 0) {
      $q.notify({
        color: 'negative',
        position: 'bottom',
        message: res.data.message,
      });
      return;
    }
    $q.notify({
      color: 'positive',
      position: 'bottom',
      message: 'success',
    });
  }
} else {
  const res = await orderPartFitment(
    editRow.value.repair_order,
    editRow.value.id,
    string
  );

  if (res.data) {
    if (res.data.code == 0) {
      $q.notify({
        color: 'negative',
        position: 'bottom',
        message: res.data.message,
      });
      return;
    }
    $q.notify({
      color: 'positive',
      position: 'bottom',
      message: 'success',
    });
  }
}

fitDiag.value = false;
initData();
emit('update');
}

function defitmentFn(row: RepairOrderParts) {
defitDialog.value = true;
editRow.value = {
  id: row.id,
  stock_code: row.stock_code,
  serial_no: row.serial_no,
};
}

async function defitment() {
const res = await orderPartDefitment(editRow.value.id);
if (res) {
  $q.notify({
    color: 'positive',
    message: `${res.data.message}`,
  });
  initData();
  emit('update');
  defitDialog.value = false;
}
}

const fail_parts = ref()

async function initData() {
const res = await getOrderParts(props.orderId);
if (res.data) {
  console.log(res.data);

  const arr = res.data.filter((item: any) => {
    return item.stock_code != props.stockCode;
  });
  parts.value = arr;
  myOrderId.value = res.data.repair_order;
}
const orderStatus = await getCheckStatus(props.orderId);
fail_parts.value = orderStatus.fail_part
console.log(fail_parts.value);
}

initData();
versionStore.init();

function getQRCODE(stock_code: string, serial_no: string) {
const obj = {
  CAT: stock_code,
  SN: serial_no,
};
return JSON.stringify(obj);
}

function printQrCode(row: RepairOrderParts) {
/*   const qr = document.getElementById('qr');
printQrImg(stock_code); */
if (row.serial_no == '') {
  $q.notify({
    message: 'No serial no, fit the part first',
    color: 'primary',
  });
  return;
}
part_id.value = row.parts
printerDiag.value = true

// window.open(`${resolveDjangoUrl()}/cews/qrcode/${row.parts}`);
}
</script>
<style scoped>
.confirm {
background-color: rgb(0, 238, 255) !important;
}

.missing {
background-color: #fff !important;
}
</style>
